/*
 * md5sum.c	- Generate/check MD5 Message Digests
 *
 * Compile and link with md5.c.  If you don't have getopt() in your library
 * also include getopt.c.  For MSDOS you can also link with the wildcard
 * initialization function (wildargs.obj for Turbo C and setargv.obj for MSC)
 * so that you can use wildcards on the commandline.
 *
 * Written March 1993 by Branko Lankester
 * Modified June 1993 by Colin Plumb for altered md5.c.
 */
#include <stdio.h>
#include <string.h>
#ifdef WIN32
#include <stddef.h>
#include "getopt.h"
#include <direct.h>
#else
#include <dirent.h>
#endif
#include "md5.h"
#include "md5sumLib.h"

#ifdef UNIX
#define	FOPRTXT	"r"
#define	FOPRBIN	"r"
#else
#ifdef VMS
#define	FOPRTXT	"r","ctx=stm"
#define	FOPRBIN	"rb","ctx=stm"
#else
#define	FOPRTXT	"r"
#define	FOPRBIN	"rb"
#endif
#endif

extern void exit(int status);
extern char *optarg;
extern int optind;

void usage();
void print_digest();
int mdfile(FILE *fp, unsigned char *digest);
int do_check(FILE *chkf);

const char *progname;
int verbose = 0;
int bin_mode = 0;
_ShowMessage_md5sum g_ShowMessage_md5sum=NULL;

static int string2Hex(char *hexstr, unsigned char *chk_digest, int len)
{
	int i=0;
	unsigned char ch=0;

	if(!hexstr||!chk_digest) return -1;
	
	for(i=0;i<2*len;i+=2){
		ch=0;
		if(hexstr[i]>='0'&&hexstr[i]<='9'){
			ch+=(hexstr[i]-'0');
		}else if(hexstr[i]>='a'&&hexstr[i]<='f'){
			ch+=(hexstr[i]-'a')+10;
		}else if(hexstr[i]>='A'&&hexstr[i]<='F'){
			ch+=(hexstr[i]-'A')+10;
		}else{
			ch+=0;
		}
		ch<<=4;
		if(hexstr[i+1]>='0'&&hexstr[i+1]<='9'){
			ch+=(hexstr[i+1]-'0');
		}else if(hexstr[i+1]>='a'&&hexstr[i+1]<='f'){
			ch+=(hexstr[i+1]-'a')+10;
		}else if(hexstr[i+1]>='A'&&hexstr[i+1]<='F'){
			ch+=(hexstr[i+1]-'A')+10;
		}else{
			ch+=0;
		}
		chk_digest[i/2]=ch;
	}

	return 0;
}

int md5Sumcheck(const char *fn, const char *pn,_ShowMessage_md5sum showMessage)
{
	char path[4096];
	int ret =0;
	FILE *fp=NULL;
	FILE *fp2=NULL;
	int number=0;
	char buf[1024];
	char *sp1=NULL;
	char *sp2=NULL;
	int i=0;
	unsigned char chk_digest[16]={0}, file_digest[16]={0};

	if(!fn||!pn) return -1;

#ifdef WIN32
	sprintf(path,"%s%s%s",pn,"\\",fn);
#else
	sprintf(path,"%s%s%s",pn,"/",fn);
#endif
	g_ShowMessage_md5sum=showMessage;
	fp=fopen(path,"rb");
	if(!fp) return -1;

	while(fgets(buf,sizeof(buf)-1,fp)){
		sp1=strtok(buf," \t");
		sp2=strtok(NULL," \t\r\n");
		if(!sp1||!sp2) continue;
		number++;
	}
	if(!number){
		fclose(fp);
		return 0;
	}

	fseek(fp,0,SEEK_SET);

	if(g_ShowMessage_md5sum) g_ShowMessage_md5sum("md5sum", "start checking.", 0);
	
	while(fgets(buf,sizeof(buf)-1,fp)){
		sp1=strtok(buf," \t");
		sp2=strtok(NULL," \t\r\n");
		if(!sp1||!sp2) continue;
		if(*sp2=='.'&&*(sp2+1)=='/') sp2+=2;
		i++;
		if(g_ShowMessage_md5sum) g_ShowMessage_md5sum("md5sum", sp2, (i*100/number)%101);
#ifdef WIN32
		sprintf(path,"%s\\%s",pn,sp2);
#else
		sprintf(path,"%s/%s",pn,sp2);
#endif
		fp2 = fopen(path, "rb");
		if(!fp2){
			ret=-1;
			break;
		}
		if(mdfile(fp2, file_digest)) {
			fclose(fp2);
			ret=-1;
			break;
		}
		fclose(fp2);

		string2Hex(sp1,chk_digest,sizeof(chk_digest));
		if (memcmp(chk_digest, file_digest, sizeof(file_digest))){
			ret=-1;
			break;
		}
	}

	fclose(fp);
	if(ret<0){
		if(g_ShowMessage_md5sum) g_ShowMessage_md5sum("md5sum", "check files failed!", -1);
	}else{
		if(g_ShowMessage_md5sum) g_ShowMessage_md5sum("md5sum", "check files successful.", 100);
	}
	if(g_ShowMessage_md5sum) g_ShowMessage_md5sum(NULL,NULL,0);

	return ret;
}

int
main_md5sum(int argc, char **argv)
{
	int opt=0;
	int rc = 0;
	int check = 0;
	FILE *fp;
	unsigned char digest[16];
	int ret=0;
#if 0
	int i=0;
#endif

	progname = *argv;
#if 0
	for(i=1;i<argc;i++){
		if(stricmp(argv[i],"-c")==0){
			check = 1;
		}else if(stricmp(argv[i],"-v")==0){
			verbose = 1;
		}else if(stricmp(argv[i],"-b")==0){
			bin_mode = 1;
		}else if(stricmp(argv[i],"-h")==0){
			usage(); return -2;
		}else{
			break;
		}
	}
	argc -= i;
	argv += i;
#endif
#ifdef WIN32
	while ((opt = pgp_getopt(argc, argv, "cbvp:h")) != EOF) {
#else
	while ((opt = getopt(argc, argv, "cbvp:h")) != EOF) {
#endif
		switch (opt) {
			case 'c': check = 1; break;
			case 'v': verbose = 1; break;
			case 'b': bin_mode = 1; break;
			default: usage(); return -2;
		}
	}
	argc -= optind;
	argv += optind;
	
	if (check) {
		if(g_ShowMessage_md5sum) g_ShowMessage_md5sum("md5sum", "start checking.", 0);
		switch (argc) {
			case 0: fp = stdin; break;
			case 1: if ((fp = fopen(*argv, FOPRTXT)) == NULL) {
					perror(*argv);
					//exit(2);
					return -2;
				}
				break;
			default: usage(); return -2;
		}
		//exit(do_check(fp));
		ret=(do_check(fp));
		if(ret<0){
			if(g_ShowMessage_md5sum) g_ShowMessage_md5sum("md5sum", "check files failed!", -1);
		}else{
			if(g_ShowMessage_md5sum) g_ShowMessage_md5sum("md5sum", "check files successful.", 100);
		}
		if(g_ShowMessage_md5sum) g_ShowMessage_md5sum(NULL,NULL,0);

		return ret;
	}
	if (argc == 0) {
		if (mdfile(stdin, digest)) {
			printf("%s: read error on stdin\n", progname);
			//exit(2);
			return -2;
		}
		print_digest(digest);
		printf("\n");
		//exit(0);
		return 0;
	}
	for ( ; argc > 0; --argc, ++argv) {
		if (bin_mode)
			fp = fopen(*argv, FOPRBIN);
		else
			fp = fopen(*argv, FOPRTXT);
		if (fp == NULL) {
			perror(*argv);
			rc = 2;
			continue;
		}
		if (mdfile(fp, digest)) {
			printf("%s: error reading %s\n", progname, *argv);
			rc = 2;
		} else {
			print_digest(digest);
			printf(" %c%s\n", bin_mode ? '*' : ' ', *argv);
		}
		fclose(fp);
	}
	//exit(rc);
	return rc;
}

void
usage()
{
	printf("usage: md5sum [-bv] [-c [file]] | [file...]\n");
	printf("Generates or checks MD5 Message Digests\n");
	printf("    -c  check message digests (default is generate)\n");
	printf("    -v  verbose, print file names when checking\n");
	printf("    -b  read files in binary mode\n");
	printf("The input for -c should be the list of message digests and file names\n");
	printf("that is printed on stdout by this program when it generates digests.\n");
	//exit(2);
}

int
mdfile(FILE *fp, unsigned char *digest)
{
	unsigned char buf[1024];
	MD5_CTX ctx;
	int n;

	MD5Init(&ctx);
	while ((n = fread(buf, 1, sizeof(buf), fp)) > 0)
		MD5Update(&ctx, buf, n);
	MD5Final(digest, &ctx);
	if (ferror(fp))
		return -1;
	return 0;
}

void
print_digest(unsigned char *p)
{
	int i;

	for (i = 0; i < 16; ++i)
		printf("%02x", *p++);
}

int
hex_digit(int c)
{
	if (c >= '0' && c <= '9')
		return c - '0';
	if (c >= 'a' && c <= 'f')
		return c - 'a' + 10;
	return -1;
}

int
get_md5_line(FILE *fp, unsigned char *digest, char *file)
{
	char buf[1024];
	int i, d1, d2, rc;
	char *p = buf;

	if (fgets(buf, sizeof(buf), fp) == NULL)
		return -1;

	for (i = 0; i < 16; ++i) {
		if ((d1 = hex_digit(*p++)) == -1)
			return 0;
		if ((d2 = hex_digit(*p++)) == -1)
			return 0;
		*digest++ = d1*16 + d2;
	}
	if (*p++ != ' ')
		return 0;
	/*
	 * next char is an attribute char, space means text file
	 * if it's a '*' the file should be checked in binary mode.
	 */
	if (*p == ' ')
		rc = 1;
	else if (*p == '*')
		rc = 2;
	else {
		printf("%s: unrecognized line: %s", progname, buf);
		return 0;
	}
	++p;
	i = strlen(p);
	if (i < 2 || i > 255)
		return 0;
	p[i-1] = '\0';
	strcpy(file, p);
	return rc;
}

int
do_check(FILE *chkf)
{
	int rc, ex = 0, failed = 0, checked = 0;
	unsigned char chk_digest[16], file_digest[16];
	char filename[256];
	FILE *fp;
	unsigned int flen = 14;
	int number=0;
	int i=0;
	int j=0;
	char buffer[1024]="";

	if(!chkf) return -1;
	while(fgets(buffer,sizeof(buffer)-1,chkf)){
		number++;
	}
	fseek(chkf,0,SEEK_SET);
	if(!number) return 1;

	while ((rc = get_md5_line(chkf, chk_digest, filename)) >= 0) {
		i++;
		if(g_ShowMessage_md5sum) g_ShowMessage_md5sum("md5sum", filename, (i*100/number)%101);
		//for(j=0;j<10000000;j++);
		if (rc == 0)	/* not an md5 line */
			continue;
		if (verbose) {
			if (strlen(filename) > flen)
				flen = strlen(filename);
			printf("%-*s ", flen, filename);
		}
		if (bin_mode || rc == 2)
			fp = fopen(filename, FOPRBIN);
		else
			fp = fopen(filename, FOPRTXT);
		if (fp == NULL) {
			printf("%s: can't open %s\n", progname, filename);
			ex = 2;
			continue;
		}
		if (mdfile(fp, file_digest)) {
			printf("%s: error reading %s\n", progname, filename);
			ex = 2;
			fclose(fp);
			continue;
		}
		
		fclose(fp);

		if (memcmp(chk_digest, file_digest, 16) != 0) {
			if (verbose)
				printf("FAILED\n");
			else
				printf("%s: MD5 check failed for '%s'\n", progname, filename);
			++failed;
		} else if (verbose)
			printf("OK\n");
		++checked;
	}
	if (verbose && failed)
		printf("%s: %d of %d file(s) failed MD5 check\n", progname, failed, checked);
	if (!checked) {
		printf("%s: no files checked\n", progname);
		return 3;
	}
	if (!ex && failed)
		ex = 1;
	return ex;
}

